package cc.ufinity.networkdiagnose.widget;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.APInfo;
import cc.ufinity.networkdiagnose.manager.ChinaNetAccount;
import cc.ufinity.networkdiagnose.manager.ChinaUnicomAccount;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.GetAPInfo;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskConfig;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class TaskDetailWidget extends GeneralTestWidget {

    private Task task;
    private Handler handler;
    private WlanManager wlanManager;
    private TelManager tm;
    private LinearLayout detailLayout;
    private Button btnBack;
    private Activity ctx;
//    private Task_Test_Widget ttw;
    private ListView wifiView;
    private EditText taskAddressText;
    private boolean updated = false;
    private boolean connecting;
    private List<APInfo> info;
    private LinearLayout taskBtnLayout;
    private Button btn;
    public static int foundApNum;
    public TaskDetailWidget(Activity context) {
        super(context);
        inflate(context, R.layout.task_detail_widget, this);
        ctx = context;
        GlobalApp.isPeapTested = false;
        detailLayout = (LinearLayout) this.findViewById(R.id.task_detail_layout);
        taskBtnLayout = (LinearLayout) this.findViewById(R.id.task_btn_layout);
        btnBack = (Button) this.findViewById(R.id.task_btnback);
        wifiView = (ListView) this.findViewById(R.id.taskWifiListView);
        taskAddressText = (EditText) this.findViewById(R.id.taskAddressText);
        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	/*if(ctx.getIntent()!=null && ctx.getIntent().getSerializableExtra("TAG_CHECK_TASK")!=null 
            			&& ((String)(ctx.getIntent().getSerializableExtra("TAG_CHECK_TASK"))).equals("checkTask")){
					ctx.getIntent().putExtra("TAG_CHECK_TASK", "");
	        		CheckWidget cw = new CheckWidget(ctx);
					cw.start();
					ctx.setContentView(cw);
	        	}else{*/
	                TaskWidget tw = new TaskWidget(ctx);
	                ctx.setContentView(tw);
	                tw.start();     
	        	//}
            }
        });
        
        wifiView.setOnItemClickListener(new OnItemClickListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	GlobalApp.taskOtherList.clear();
				GlobalApp.index = 0;
				
            	Map<String, Object> r = (Map<String, Object>) wifiView.getAdapter().getItem(position);
                selectedScanResult = (ScanResult) r.get("scan");
                
            	List<ScanResult>  scanResultList =  wlanManager.getScanResults();
            	List<ScanResult> CN_CU_ScanResults = selectOther2(scanResultList);
            	if(CN_CU_ScanResults.size() > 0) {//成立表示有电信或联通或者二者都有的无线AP
            		DBManager db = new DBManager(ctx);
    				ChinaNetAccount  china = db.getChinaNetAccount();
    				ChinaUnicomAccount unicom = db.getUnicomAccount();
    				db.release();
            		Task t;
            		if(china != null && china.userName != null && china.userName.length()>10) {
            			for(int i=0; i<CN_CU_ScanResults.size(); i++) {
                    		//for(int i=0; i<3; i++) {
                        		ScanResult scanResult = CN_CU_ScanResults.get(i);
                        		//ScanResult scanResult = selectedScanResult;
                        		if(scanResult.SSID.equals(WlanManager.SSID_ChinaNet) && scanResult.level >= -70) {
                        			t = new Task();
                        			t.scanResult = scanResult;
                            		t.mac = scanResult.BSSID;
                            		t.id = task.id;
                            		t.httpTasks = task.httpTasks;
                					t.ftpTasks = task.ftpTasks;
                					t.pingTasks = task.pingTasks;
                					t.testCount = task.testCount;
                					t.taskType = task.taskType;
                					t.selNetType = task.selNetType;
                            		
                            		GlobalApp.taskOtherList.add(t);
                        		}
                    		}
            		} 
            		if(unicom != null && unicom.userName != null && unicom.userName.length()>10) {
            			for(int i=0; i<CN_CU_ScanResults.size(); i++) {
                    		//for(int i=0; i<3; i++) {
                        		ScanResult scanResult = CN_CU_ScanResults.get(i);
                        		//ScanResult scanResult = selectedScanResult;
                        		if((scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom1) || scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom2))
    	            					&& scanResult.level >= -70) {
                        			t = new Task();
                        			t.scanResult = scanResult;
                            		t.mac = scanResult.BSSID;
                            		t.id = task.id;
                            		t.httpTasks = task.httpTasks;
                					t.ftpTasks = task.ftpTasks;
                					t.pingTasks = task.pingTasks;
                					t.testCount = task.testCount;
                					t.taskType = task.taskType;
                					t.selNetType = task.selNetType;
                            		
                            		GlobalApp.taskOtherList.add(t);
                        		}
                    		}
            		}
            		
            	}
            	
            	
                // String lock = (String) r.get("lock");
                // if ("true".equals(lock)) {
                // showMessage(ctx, "此项已测过.");
                // } else {
                if(selectedScanResult !=null){
                    task.scanResult = selectedScanResult;
                    task.mac = selectedScanResult.BSSID;
                    enableNetWork(selectedScanResult);
                }
                // }
            }
        });
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
					updateWifi();
                    if (!updated) {
                        updated = true;
                        dismissMessageDialog();
                    }
                    break;
                case MessageWhat.WIFI_SUCESS_CONNECTED:
                //    initTask();  
                	if(task.acIp==null || task.acIp.equals(""))
                		task.acIp = wlanManager.getIpAddress(); 
        			ctx.getIntent().putExtra(TAG_REFER_TASK, task);
        			
                    /*ttw = new Task_Test_Widget(ctx);
                    ctx.setContentView(ttw);*/
                    
                    dismissMessageDialog();
                    GlobalApp.taskWlan = task;
                   /* if(task.taskType != null && task.taskType.trim().equals("巡检测试")) {
                    	TaskTestWlan2Widget ttw = new TaskTestWlan2Widget(ctx);
                        ctx.setContentView(ttw);
                    }  else {*/
                    	TaskTestWlanWidget ttww = new TaskTestWlanWidget(ctx);
                        ctx.setContentView(ttww);
                  //  }
                    //获取city、town
                    System.out.println("-----------   获取city、town");
                    new GetAPInfo(task.mac).start();
                    if(GlobalApp.CITY == null || GlobalApp.CITY.length() < 2) {
                    	new GetAPInfo(tm.getPhoneNumber(), false).start3();
                    }
                    break;

                case MessageWhat.ACCOUNT_INFO_INVALID:
                    showMessage(ctx, "CMCC账号无效，请确认是否配置.");
                    dismissMessageDialog();
                    break;
                case MessageWhat.ACCOUNT_LOGIN_INVALID:
                    showMessage(ctx, "CMCC账号登录失败.");
                    dismissMessageDialog();
                    break;
                case MessageWhat.WIFI_CONNECT_TIMEOUT:
                    connecting = false;
                    dismissMessageDialog();
                    showMessage(ctx, "连接网络超时，请重试.");
                    break;
                case MessageWhat.TASK_BEGIN:
                    doTest();
                    break;
                case MessageWhat.TASK_APINFO_LOADED:
                    showTaskNum();
                    break;
                }
            }
        };
        tm = new TelManager(ctx);
        tm.setHandler(handler);
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        wlanManager.task = task;
        prepare();
    }

    private void prepare() {
        init();
        if (task.selNetType == ConnectivityManager.TYPE_WIFI) {
            this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
            new Thread() {
                public void run() {
                  //  loadAPInfo();
                    wlanManager.startScan();
                }
            }.start();
        	
        } else {

            btn = new Button(ctx);
//            btn.setText("开始测试");
            btn.setTextColor(Color.WHITE);
            btn.setBackgroundResource(R.drawable.btn_dblue);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String address = taskAddressText.getText().toString();
                    if (StringUtils.isEmpty(address)) {
                        showMessage(ctx, "请输入当前测试地点.");
                        return;
                    }else  if (getFTPConfig(ctx)== null) {
            			showMessage(ctx, "获取FTP账号失败，请检查FTP配置是否正确.");
            			return;
            		} else {
                        task.taskAddress = address;
                        if (btn!=null) {
    						btn.setClickable(false);
    					}
          		      //获取city、town
                        System.out.println("-----------   获取city、town");
        			    TelManager tm = new TelManager(ctx);
        		        int lac = tm.getLac();
        		        int ci = tm.getCI();
        		        new GetAPInfo(lac,ci).start2();
                        if(GlobalApp.CITY == null || GlobalApp.CITY.length() < 2) {
                        	new GetAPInfo(tm.getPhoneNumber(), false).start3();
                        }
                        initTask();
                    }
                }

            });
            taskBtnLayout.addView(btn);
        }
    }
 
    private void showTaskNum() {
        if (info.size() > 0) {
            DBManager db = new DBManager(ctx);
            List<TaskConfig> configs = db.getTask(task.apName, String.valueOf(task.id));
            db.release();
            StringBuffer s = new StringBuffer();
            s.append("当前热点下共有 ").append(info.size()).append(" 项测试，已完成  ")
            	.append(configs.size()).append(" 项.");
            TextView tv = new TextView(ctx);
            tv.setText(s);
            tv.setTextSize(14);
            tv.setTextColor(Color.GRAY);
            detailLayout.addView(tv);
        }
    }

    @Deprecated
    private void startConnectTimeoutListener() {
        TimerTask wifiReceiverTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);
    }

    private void enableNetWork(final ScanResult scan) {
        String address = taskAddressText.getText().toString();
        if (StringUtils.isEmpty(address)) {
            this.showMessage(ctx, "请输入当前测试地点.");
            return;
        }
        if (getFTPConfig(ctx)== null) {
			showMessage(ctx, "获取FTP账号失败，请检查FTP配置是否正确.");
			return;
		}
        task.taskAddress = address;
        showMessageDialog(ctx, "正在连接Wifi热点...");
        connecting = true;
        // startConnectTimeoutListener();
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

        // 登录认证
        // DBManager db = new DBManager(ctx);
        // Account account = db.getAccount();
        // if (account == null) {
        // Message m = new Message();
        // m.what = MSG_ACCOUNT_INVALID;
        // hander.sendMessage(m);
        // } else {
        // WebAuthManager wm = new WebAuthManager(ctx);
        // connected = wm.auth("http://www.baidu.com", account.userName,
        // account.password);
        // if (!connected) {
        // Message m = new Message();
        // m.what = MSG_LOGIN_INVALID;
        // hander.sendMessage(m);
        // }
        // }
    }

    private void doTest() {
        dismissMessageDialog();
        task.startTime = StringUtils.getDateTime();
      /*  HttpTestWidgetProxy tw = new HttpTestWidgetProxy(ctx);
        ctx.setContentView(tw);*/
   //     ctx.setContentView(new Task_Test_Widget(ctx));

        ctx.getIntent().putExtra(TAG_REFER_TASK, task);
        
        if(task.selNetType == ConnectivityManager.TYPE_MOBILE_MMS) {
        	GlobalApp.taskTD = task;
        	ctx.setContentView(new TaskTestTDWidget(ctx));
        } else if(task.selNetType == ConnectivityManager.TYPE_MOBILE) {
        	GlobalApp.taskGSM = task;
        	ctx.setContentView(new TaskTestGSMWidget(ctx));
        }
    }

    private void initTask() {
        this.initTask(task, ctx, task.selNetType);
        ctx.getIntent().putExtra(TAG_REFER_TASK, task);
        wlanManager.sendMsg(MessageWhat.TASK_BEGIN);
        
    }
    class ComparatorUser implements Comparator {

		public int compare(Object arg0, Object arg1) {
			Map<String, Object> user0 = (Map<String, Object>) arg0;
			Map<String, Object> user1 = (Map<String, Object>) arg1;
			String a = (String) user0.get("level");
			String b = (String) user1.get("level");
			String str1 = a.toString().replace("-", "");
			String sss1 = str1.replace("dBm", "");

			String str2 = b.toString().replace("-", "");
			String sss2 = str2.replace("dBm", "");
			int flag = 0;
			try {
				int num1 =Integer.parseInt(sss1.trim());
				int num2 =Integer.parseInt(sss2.trim());
				flag = num1 - num2;
			} catch(Exception e) { }
			
			return flag;
		}
	}
    
   
	public void updateWifi() {
    	
        List<Map<String, Object>> data = null;
         
//---------------------------------------------------------------
    	if(true) {
    		data = wlanManager.getWifiList();
    	} /*else {
    		List<Map<String, Object>> data1 = wlanManager.getWifiList();
            List<Map<String, Object>> data2 = new ArrayList<Map<String,Object>>();
            data = new ArrayList<Map<String,Object>>();
    		foundApNum = 0;
    		int num=0 ;
            for(Map<String, String[]> t : task.apList){
            	Iterator it= t.entrySet().iterator();
        		while(it.hasNext())
        		{
        			Map.Entry entry1 = (Map.Entry) it.next();   
        			String ky = (String)entry1.getKey();   
        			String[] vl = (String[])entry1.getValue();
        			System.err.println(ky+":Mac");
        			boolean flag = false;
        			for(Map<String, Object> ap : data1) {
        				String listedMac =(String)ap.get("mac"); 
    	    			if(ky.toLowerCase().equals(listedMac.toLowerCase()))
    	    			{
    		    			System.err.println(ky+":===============:"+listedMac);
    		    			ap.put("ssid", vl[0]);
    	    				data.add(ap);
    	    				flag = true;
    	    				num++;
    	    				break;
    	    			}
        		    } 
        			if(!flag){
        				   Map<String, Object> map = new HashMap<String, Object>();
        				   map.put("ssid", vl[0]);
        				   map.put("mac", ky);
        				   map.put("level", 0+" dBm");
        				   map.put("img", R.drawable.xh1);
        				   map.put("scan", null);
        				   data2.add(map);
        			}else {
        				foundApNum++;
        			}
        				
        		}
            }  
            Collections.sort(data, new ComparatorUser());  //  level排序
            data.addAll(data2); 
    	}*/
    	
    	List<Map<String, Object>> data2 = new ArrayList<Map<String,Object>>();
    	for(int i=0;i<data.size();i++){
    		Map<String, Object> map=data.get(i);
    		if(map.get("ssid").toString().startsWith("CMCC")){
    			data2.add(map);
    		} 
    	}
    	Collections.sort(data2, new ComparatorUser()); 
    	
//---------------------------------------------------------------data包含全部data2包涵的是只有CMCC   
         
        SimpleAdapter adapter = new SimpleAdapter(ctx, data2, R.layout.wifi_list_widget, 
        		new String[] { "ssid", "mac", "img", "level" }, 
        		new int[] {R.id.wifi_ssid, R.id.wifi_mac, R.id.wifi_img, R.id.wifi_level }) {
        	  
             public View getView(int position, View convertView, ViewGroup parent){ 
        		 convertView = null;
        		 convertView = super.getView(position, convertView, parent);   
        		 this.getCount();
//        		 System.err.println( this.getCount()+"###################################################"+position);
        		 if(position >= TaskDetailWidget.foundApNum){
        			 TextView tempView =  (TextView)convertView.findViewById(R.id.wifi_ssid);
                  	if(tempView != null){
                 		tempView.setTextColor(Color.GRAY);
                 	}
                  	tempView = (TextView)wifiView.findViewById(R.id.wifi_mac);
                 	if(tempView != null)
                 		tempView.setTextColor(Color.GRAY);
                 	tempView =  (TextView)wifiView.findViewById(R.id.wifi_level);
                 	if(tempView != null)
                 		tempView.setTextColor(Color.GRAY);  
        		 }
        		 return convertView;
             }  
        } ;  
// SimpleAdapter adapter = new SimpleAdapter(ctx, data, R.layout.wifi_list_widget, 
//		new String[] { "ssid", "mac", "img", "level" }, 
//		new int[] {R.id.wifi_ssid, R.id.wifi_mac, R.id.wifi_img, R.id.wifi_level });
        wifiView.setAdapter(adapter);  
    }

    private void init() {
        String labelTaskName = this.getResources().getString(R.string.label_task_name);
        String labelApName = this.getResources().getString(R.string.label_apname);
        String labelTaskType = this.getResources().getString(R.string.label_task_type);
        String labelTaskDesc = this.getResources().getString(R.string.label_task_desc);
        String labelTaskRemark = this.getResources().getString(R.string.label_task_remark);
        String labelTaskMan = this.getResources().getString(R.string.label_task_man);
        String labelTaskId = this.getResources().getString(R.string.label_task_id);
        StringBuffer s = new StringBuffer();
        s.append(labelTaskId + " " + task.id).append('\n');
        s.append(labelTaskMan + " " + task.taskMan).append('\n');
        s.append(labelTaskName + " " + task.taskName).append('\n');
        s.append(labelApName + " " + task.apName).append('\n');
        s.append(labelTaskType + " " + task.taskType).append('\n');
        s.append(labelTaskDesc + " " + task.taskDes).append('\n');
        s.append(labelTaskRemark + " " + task.remark);
        TextView tv = new TextView(ctx);
        tv.setTextColor(Color.GRAY);
    //    tv.setText(labelTaskId + task.id);  
        tv.setText(s);
        detailLayout.addView(tv);

    }

}
